package com.hmdp.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 *
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //json转换
    final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Result queryTypeList() {

        UserDTO user = UserHolder.getUser();
        String key = "shop:list:" +user;

        //从redis中查询商铺缓存
        //List<ShopType> shopTypeJson = stringRedisTemplate.opsForList().range(key,0,-1).stream().map(x->JSONUtil.toBean(x,ShopType.class)).collect(Collectors.toList());

        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if (shopTypeJson==null) {
            //存在则返回,将json转成对象
            ShopType shopType = JSONUtil.toBean(shopTypeJson, ShopType.class);
            return Result.ok(shopType);
        }

        //不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();

        //数据库找不到，返回错误
        if(typeList==null){
            return Result.fail("商铺列表不存在");
        }

        //存在，先转成json再写入redis
        //list转为json
        String listJson = JSONUtil.toJsonStr(typeList);

        stringRedisTemplate.opsForValue().set(key,listJson,30, TimeUnit.MINUTES);
        //返回
        return Result.ok(typeList);
    }
}
